// import request from '@/utils/request'
import { type FullRequestParams, Api as _Api } from "./_Api";
import { getToken } from "../utils/cache";
import { showFailToast } from "vant";
import { router } from "../router";

export const ApiAll = new _Api();
const request = ApiAll.request;
ApiAll.request = (config: FullRequestParams) => {
  const token = getToken();
  config.headers = config.headers || {};
  config.cache = "no-store";
  config.baseUrl = import.meta.env.VITE_AJAX_BASE;
  const headers = config.headers as { [key: string]: string };
  if (token && !headers.Authorization) {
    headers.Authorization = token;
  }
  config.headers = Object.assign(config.headers || {}, {});
  return request(config).then(async (data) => {
    if (
      data.status > 299 ||
      data.status < 200 ||
      (data.data && data.data.code !== 200)
    ) {
      showFailToast(String(data.data.msg || "") || "失败~");
      if (data.data.code === 401) {
        const f = router.currentRoute.value.fullPath;
        let baseHref = location.origin + import.meta.env.VITE_BASE_PATH;
        baseHref = baseHref.endsWith("/") ? baseHref.slice(0, -1) : baseHref;
        const url = "/login?redirect=" + (f.startsWith("/login") ? "/" : f);
        location.href = baseHref + url;
      }
      throw new Error(data.data.msg || data);
    } else {
      return data;
    }
  });
};
export const API = ApiAll.api;
